package com.chenken.single;

import com.chenken.AbstractList;
/**
 * 
 *	单向链表
 * @param <E>
 */
public class SingleLinkedList<E> extends AbstractList<E>{
	
	private Node<E> first;
	
	private static final int ELEMENT_NOT_FOUND = -1;

	@Override
	public void clear() {
		first = null;
		size = 0;
	}

	@Override
	public boolean contains(E element) {
		return false;
	}

	@Override
	public E set(int index, E element) {
		Node<E> node = node(index);
		E old = node.element;
		
		node.element = element;
		return old;
	}

	@Override
	public void add(int index, E element) {
		if(index == 0) {
			/**
			 * 	将以前的first作为新node的next
			 * 	将first指针指向新节点
			 */
			first = new Node<E>(element, first);
		}else {
			Node<E> preNode = node(index-1);
			preNode.next = new Node<E>(element, preNode.next);
		}
		size++;
	}

	@Override
	public E remove(int index) {
		Node<E> node = first;
		if(index == 0) {
			first = first.next;
		}else {
			Node<E> preNode = node(index-1);
			node = preNode.next;
			preNode.next = node.next;
		}
		size--;
		return node.element;
	}

	@Override
	public int indexOf(E element) {
		if(element == null) {
			Node<E> node = first;
			for(int i = 0;i<size;i++) {
				if(node.element == null) return i;
				node = node.next;
			}
		}else{
			Node<E> node = first;
			for(int i = 0;i<size;i++) {
				if(element.equals(node.element)) return i;
				node = node.next;
			}
		}
		return ELEMENT_NOT_FOUND;
	}
	
	@Override
	public E get(int index) {
		return node(index).element;
	}
	
	private Node<E> node(int index){
		rangeCheck(index);
		Node<E> node = first;
		for(int i = 0;i<index;i++) {
			node = node.next;
		}
		return node;
	}
	
	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("size=").append(size).append(",[");
		Node<E> node = first;
		for(int i = 0;i<size;i++) {
			if(i!=0) {
				stringBuilder.append(",");
			}
			stringBuilder.append(node.element);
			node = node.next;
		}
		stringBuilder.append("]");
		return stringBuilder.toString();
	}
	
	private static class Node<E>{
		
		E element;
		
		Node<E> next;

		public Node(E element, Node<E> next) {
			this.element = element;
			this.next = next;
		}
	}
	
	
}
